package liuwh.mina.basic.tcp.server.tiemserver.client;

import java.net.InetSocketAddress;

import liuwh.mina.basic.tcp.server.tiemserver.codec.TimeResponseCodecFactory;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.future.WriteFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

public class TimeClient {
	
	public static void main(String[] args) {
		IoConnector connector = new NioSocketConnector();
		
		connector.getFilterChain().addLast("logger", new LoggingFilter());
		
		connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TimeResponseCodecFactory(false)));
		
		connector.setHandler(new ClientHandler());
		
		ConnectFuture cf = connector.connect(new InetSocketAddress("127.0.0.1", 8985));
		cf.awaitUninterruptibly();
		
		IoSession session = cf.getSession();
		WriteFuture f = session.write("abc123");
		
		session.getCloseFuture().join() ;
		
		connector.dispose() ;
		
		// 关得太快了，响应消息都还没处理
//		session.close(false);		// true : 不管请求消息有没有发送完都关闭；false : 待请求消息发送完再关闭，不管响应消息
//		connector.dispose();
	}
	
}
